<script setup>
import { useAppStore, useWMSStore } from '@/stores'
import ExceptionLogger from '@/utils/errorHandler'
import { useBoolean } from '@/hooks/useBoolean'

const appStore = useAppStore()
const wmsStore = useWMSStore()
const selectedValue = ref('选择要加载的WMS图层')
const fileInput = ref(null)
const fileName = ref('') // 用于存储文件名
const fileError = ref(false) // 用于控制文件名颜色
const layerOptions = ref([])
const loading = ref(false)
const windowWidth = ref(window.innerWidth)
const windowHeight = ref(window.innerHeight)
const adaptHeight = appStore.showTabs ? (appStore.showFooter ? ref(387) : ref(427)) : appStore.showFooter ? ref(427) : ref(472)
const { bool: addLoading, setTrue: startLoading, setFalse: endLoading } = useBoolean(false)
const computedHeight = computed(() => windowHeight.value - adaptHeight.value + 210)
const wmsInfo = reactive({
  Provider: {
    title: '提供商:',
    value: ''
  },
  WMSType: {
    title: 'WMS版本:',
    value: ''
  },
  Title: {
    title: '图层名:',
    value: ''
  },
  BoundingBox: {
    title: '范围:',
    value: ''
  }
})
const handleResize = () => {
  windowWidth.value = window.innerWidth
  windowHeight.value = window.innerHeight
}

const currentLayerAndWmsInfo = computed(() => ({
  currentLayer: wmsStore.currentLayer,
  layers: wmsStore.wmsInfo.layer
}))

async function handleUpdateValue(_, option) {
  startLoading()
  try {
    wmsStore.setCurrentLayer(option.label)
    await wmsStore.setLeafletAddCode()
    await wmsStore.setOpenlayersAddCode()
    await wmsStore.setCesiumAddCode()
    await wmsStore.setSuperMap3DAddCode()
  } catch (error) {
    fileError.value = true
    ExceptionLogger.wmsHandleException(error)
  } finally {
    endLoading()
  }
}

// 打开文件选择器
function selectFile() {
  fileInput.value.click()
}

// 处理文件选择
async function handleFileChange(event) {
  const file = event.target.files[0]
  if (file) {
    fileError.value = false
    fileName.value = file.name
    const reader = new FileReader()
    reader.onload = async (e) => {
      const fileContent = e.target.result
      startLoading()
      try {
        await wmsStore.initWMSInfoByFile(fileContent)
        await wmsStore.setLeafletAddCode()
        await wmsStore.setOpenlayersAddCode()
        await wmsStore.setCesiumAddCode()
        await wmsStore.setSuperMap3DAddCode()
      } catch (error) {
        fileError.value = true
        ExceptionLogger.wmsHandleException(error)
      } finally {
        loading.value = false
        endLoading()
      }
    }
    reader.readAsText(file)
  }
}

onMounted(() => {
  window.addEventListener('resize', handleResize)
})

onUnmounted(() => window.removeEventListener('resize', handleResize))

watch(currentLayerAndWmsInfo, ({ currentLayer, layers }) => {
  if (currentLayer) {
    wmsInfo.Provider.value = wmsStore.wmsInfo.provider
    wmsInfo.WMSType.value = wmsStore.wmsInfo.wmsType
    wmsInfo.Title.value = currentLayer.title
    wmsInfo.BoundingBox.value = JSON.stringify(currentLayer.boundingBox)
  }
  if (layers && layers.length > 0) {
    selectedValue.value = layers[0].title
    layerOptions.value = layers.map((item) => ({
      label: item.title,
      value: item.name
    }))
  }
})

watch(
  () => appStore.showTabs,
  () => (appStore.showTabs ? (adaptHeight.value += 45) : (adaptHeight.value -= 45)),
  { immediate: true }
)

watch(
  () => appStore.showFooter,
  () => (appStore.showFooter ? (adaptHeight.value += 40) : (adaptHeight.value -= 40)),
  { immediate: true }
)
</script>

<template>
  <n-card>
    <n-grid :x-gap="0" :y-gap="8" :cols="2">
      <n-gi>
        <n-flex>
          <n-input-group>
            <div style="display: flex; align-items: center; min-width: 400px">
              <n-button type="primary" :loading="loading" @click="selectFile">
                <template #icon>
                  <icon-park-outline-data />
                </template>
                选择文件
              </n-button>
              <span :style="{ color: fileError ? 'red' : '#18a058' }" style="margin-left: 10px" v-if="fileName">{{ fileName }}</span>
              <input type="file" ref="fileInput" style="display: none" @change="handleFileChange" accept=".xml" />
            </div>
          </n-input-group>
        </n-flex>
      </n-gi>
      <n-gi>
        <n-flex class="w-80 ml-auto">
          <n-select v-model:value="selectedValue" @update:value="handleUpdateValue" filterable :options="layerOptions" />
        </n-flex>
      </n-gi>
    </n-grid>
  </n-card>
  <n-card embedded :style="{ height: `${computedHeight}px` }" class="flex-1 mt-2">
    <n-list hoverable bordered>
      <n-list-item v-for="(item, index) in wmsInfo" :key="index">
        <n-thing :title="item.title" content-style="margin-top: 10px;" :style="{ color: appStore.primaryColor }">
          <template #description>
            {{ item.value }}
            <copy-text v-model:value="item.value"></copy-text>
          </template>
        </n-thing>
      </n-list-item>
    </n-list>
    <Loading v-if="addLoading" />
  </n-card>
</template>
